<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;

class Warehouse extends Model
{

    // 表名
    protected $name = 'kuyou_warehouse';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$sort_field,$sort_type){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->page($page,$limit)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            business_type,number,price,customers_id,preparation_id,examine_id,examine_status,remarks,print_num")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            business_type,number,price,customers_id,preparation_id,examine_id,examine_status,remarks,print_num")->select())->toArray();
        }
        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['customers'] = (new Customers())->where(['id'=>$list_v['customers_id']])->value('customer_name');
            $list[$list_k]['preparation_name'] = (new User())->where(['id'=>$list_v['preparation_id']])->value('username');
            $list[$list_k]['examine_name'] = (new User())->where(['id'=>$list_v['examine_id']])->value('username');
            unset($list[$list_k]['preparation_id']);
            unset($list[$list_k]['examine_id']);

            $where = [];
            $where['purchase_code'] = $list_v['purchase_code'];
            $info_list = Db::name('kuyou_warehouse_info')->alias('po')
                ->join('kuyou_goods g','g.id=po.goods_id')
                ->where($where)
                ->field("g.goods_code,g.goods_name,g.goods_image,po.number,
            po.basic_nmber,po.unit_price,po.price")->select();
            $list[$list_k]['info_list'] = $info_list;
        }
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param string $purchase_code
     * @return array
     */
    public static function getDetail($purchase_code){
        $detail = self::where(function ($query) use ($purchase_code) {
            $query->where('purchase_code', '=', $purchase_code);
        })->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            business_type,number,price,customers_id,preparation_id,examine_id,examine_status,remarks,print_num,order_id,order_type")->find();
        if($detail){
            $detail['customers'] = (new Customers())->where(['id'=>$detail['customers_id']])->value('customer_name');
            $where = [];
            $where['purchase_code'] = $detail['purchase_code'];
            $info_list = Db::name('kuyou_warehouse_info')->alias('po')
                ->join('kuyou_goods g','g.id=po.goods_id')
                ->join('kuyou_unit u','u.id=po.goods_unit')
                ->join('kuyou_stores s','s.id=po.stores_id')
                ->where($where)
                ->field("po.id,po.purchase_code,FROM_UNIXTIME(po.purchase_time,'%Y-%m-%d') as purchase_time,
            g.goods_code,g.goods_name,g.goods_image,g.batch as batch_status,g.serial as serial_status,
            po.goods_attr,po.goods_unit,u.name as unit_name,po.stores_id,s.name as stores_name,po.number,po.stock,
            po.basic_nmber,po.unit_price,po.period,po.price,po.remark,po.batch,po.batch_id,po.manufacture,po.guarantee,po.validity")->select();
            foreach ($info_list as $info_list_k=>$info_list_v){
                if(!empty($info_list_v['period'])){
                    $info_list[$info_list_k]['period'] = unserialize($info_list_v['period']);
                }else{
                    $info_list[$info_list_k]['period'] = [];
                }
                if(!empty($info_list_v['manufacture'])){
                    $info_list[$info_list_k]['manufacture'] = date('Y-m-d',$info_list_v['manufacture']);
                }
                if(!empty($info_list_v['validity'])){
                    $info_list[$info_list_k]['validity'] = date('Y-m-d',$info_list_v['validity']);
                }
                
                $info_list[$info_list_k]['attr_name'] = '';
                if(!empty($info_list_v['goods_attr'])){
                    $attribute_id = Db::name('kuyou_goods_attr')->where(['id'=>$info_list_v['goods_attr']])->value('attribute_id');
                    $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$attribute_id])->value('attr_ids');
                    if($attribute_ids){
                        $attribute_ids = explode('&',$attribute_ids);
                        $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                        $info_list[$info_list_k]['attr_name'] = implode('/',$attribute);
                    }
                }
            }
            $detail['info_list'] = $info_list;
        }
        if(!empty($detail)){
            if(!empty($detail['cost_data'])){
                $detail['cost_data'] = (array)json_decode($detail['cost_data'], true);
            }
            return ['status'=>200,'msg'=>$detail];
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'business_type|业务类别'=>'require|in:1,2',
                'info_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],18);//验证编号是否合法
                if($status){
                    $examine= (new Commons())->getSet('examine','is_checked');
                    $code = $detail['purchase_code'];
                    $purchase_time = strtotime($detail['purchase_time']);
                    $business_type = $detail['business_type'];

                    $detail['info_list'] = (array)json_decode($detail['info_list'], true);
                    $supplyer = Db::name('kuyou_customers')->where(['id'=>$detail['customers_id']])->find();
                    $serial= Db::name('kuyou_sets')->where(['name'=>'serial'])->value('is_checked');
                    $batch= Db::name('kuyou_sets')->where(['name'=>'batch'])->value('is_checked');

                    $data = [];
                    $all_number = 0;//总数量
                    $all_price = 0;//总金额
                    foreach ($detail['info_list'] as $k=>$v){
                        if(!empty($v['goods_code'])){//有产品编号
                            if(!isset($v['stores_id']) || empty($v['stores_id'])){
                                return ['status'=>500,'msg'=>'请选择仓库'];
                            }
                            if(!isset($v['number']) || empty($v['number'])){
                                return ['status'=>500,'msg'=>'请输入出库数量'];
                            }
                            $all_number += (float)$v['number'];
                            $all_price += (float)$v['all_money'];

                            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->find();
                            $goods_unit = $v['goods_unit']===''?null:(float)$v['goods_unit'];
                            if(empty($goods_unit)){
                                return ['status'=>500,'msg'=>'请选择单位'];
                            }

                            $advance_rate = 1;//换算进率
                            if($goods['more_unit']==1) {
                                if($goods_unit!=$goods['unit_id']){
                                    //所选单位不等于商品默认单位，需查询进率换算基础数量
                                    $more_unit = Db::name('kuyou_unit_conversion')
                                        ->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$goods_unit])
                                        ->field('id,advance_rate')
                                        ->find();
                                    if(empty($more_unit)){
                                        return ['status'=>500,'msg'=>'商品单位信息查询失败'];
                                    }else{
                                        $advance_rate = $more_unit['advance_rate'];
                                    }
                                }
                            }

                            if($goods['batch']==1 && $batch==1) {
                                if (empty($v['batch_id'])) {
                                    return ['status'=>500,'msg'=>'请选择生产批次'];
                                }
                                if (empty($v['manufacture'])) {
                                    return ['status'=>500,'msg'=>'请输入生产日期'];
                                }
                                if (empty($v['guarantee'])) {
                                    return ['status'=>500,'msg'=>'请输入保质期'];
                                }
                                if (empty($v['validity'])) {
                                    return ['status'=>500,'msg'=>'请输入过期时间'];
                                }
                                $where = [];
                                $where['goods_code'] = $goods['goods_code'];
                                $where['stores_id'] = (float)$v['stores_id'];
                                if(!empty($v['goods_attr'])){
                                    $where['attribute_id'] = (float)$v['goods_attr'];
                                }
                                $where['batch_id'] = (float)$v['batch_id'];
                                $basic_nmber = round(($advance_rate*$v['number']),4);

                                $batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                                if(empty($batch_stock)){
                                    return ['status'=>500,'msg'=>'批次信息查询错误'];
                                }elseif ($batch_stock['stock']<$basic_nmber){
                                    return ['status'=>500,'msg'=>'此批次库存不足'];
                                }
                            }
                            if(isset($v['period_period']) && $goods['serial']==1 && $serial==1){
                                if(empty($v['period_period'])){
                                    return ['status'=>500,'msg'=>'请输入商品序列号'];
                                }
                                $basic_nmber = (float)$v['number'];

                                $per_code = [];
                                $period = $v['period_period'];
                                foreach ($period as $period_k=>$period_v){
                                    if(!in_array($period_v['serial'],$per_code)){
                                        $per_code[] = $period_v['serial'];
                                    }
                                }
                                $per_s = Db::name('kuyou_goods_serial')->where(['serial'=>['in',$per_code],'store_status'=>'1'])->column('serial');
                                if(sizeof($per_code)!=sizeof($per_s)){
                                    $str = [];
                                    foreach ($per_code as $per_code_k=>$per_code_v){
                                        if(!in_array($per_code_v,$per_s)){
                                            $str[] = $per_code_v;
                                        }
                                    }
                                    return ['status'=>500,'msg'=>'序列号'.implode(',',$str).'不在库，不可出库'];
                                }
                            }else{
                                $basic_nmber = round(($advance_rate*$v['number']),4);
                            }

                            $data[] = [
                                'purchase_code'     =>  $code,
                                'purchase_time'     =>  $purchase_time,

                                'goods_id'          =>  $goods['id'],
                                'goods_attr'        =>  $v['goods_attr']===''?null:(float)$v['goods_attr'],
                                'goods_unit'        =>  $goods_unit,
                                'stores_id'         =>  $v['stores_id']===''?null:(float)$v['stores_id'],
                                'stock'             =>  $v['allow_stock']===''?null:(float)$v['allow_stock'],
                                'number'            =>  $v['number']===''?null:(float)$v['number'],
                                'basic_nmber'       =>  $basic_nmber,
                                'period'            =>  $v['period_period']===''?null:(is_array($v['period_period'])?serialize($v['period_period']):$v['period_period']),
                                'unit_price'        =>  $v['unit_price']===''?null:(float)$v['unit_price'],
                                'price'             =>  $v['all_money']===''?null:(float)$v['all_money'],

                                'remark'            =>  $v['remark']===''?null:$v['remark'],
                                'batch'             =>  $v['batch_name']===''?null:$v['batch_name'],
                                'batch_id'          =>  $v['batch_id']===''?null:(float)$v['batch_id'],
                                'manufacture'       =>  $v['manufacture']===''?null:strtotime($v['manufacture']),
                                'guarantee'         =>  $v['guarantee']===''?null:(float)$v['guarantee'],
                                'validity'          =>  $v['validity']===''?null:strtotime($v['validity']),

                                'createtime'        => time(),
                                'updatetime'        => time(),
                            ];
                        }
                    }
                    if(!empty($data)){
                        $rowdata = [
                            'purchase_code'     => $code,
                            'purchase_time'     => $purchase_time,
                            'business_type'     => $business_type,
                            'number'            => $all_number,
                            'price'             => $all_price,
                            'customers_id'      => isset($supplyer['id'])?$supplyer['id']:null,
                            'preparation_id'    => $adminId,
                            'remarks'           => $adminId,
                            'order_id'          => isset($detail['order_id'])?$detail['order_id']:null,
                            'order_type'        => isset($detail['order_type'])?(empty($detail['order_type'])?null:$detail['order_type']):null,
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }

                    $model = new Warehouse();
                    $row = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                    }
                    $result = false;
                    Db::startTrans();
                    try {
                        $model->allowField(true)->save($rowdata);
                        $result = $model->id;

                        if(!empty($data)){
                            Db::name('kuyou_warehouse_info')->insertAll($data);
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($result){
                        if($examine!=1){
                            try {
                                $exa = self::examine($detail['purchase_code']);
                            } catch (Exception $e) {
                            }
                            if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                try {
                                    self::delDetail($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                return ['status'=>500,'msg'=>$exa['msg']];
                            }
                        }
                        return ['status'=>200,'msg'=>$detail['purchase_code']];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'old_purchase_code|原单据编号'=>'require',
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'business_type|业务类别'=>'require|in:1,2',
                'info_list|详细信息'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],18);//验证编号是否合法
                if($status){
                    $model = new Warehouse();
                    $row = $model->where(['purchase_code'=>$detail['old_purchase_code']])->find();
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'修改的单据不存在'];
                    }
                    $old_purchase_code = $detail['old_purchase_code'];

                    $examine= (new Commons())->getSet('examine','is_checked');
                    $code = $detail['purchase_code'];
                    $purchase_time = strtotime($detail['purchase_time']);
                    $business_type = $detail['business_type'];

                    $detail['info_list'] = (array)json_decode($detail['info_list'], true);
                    $supplyer = Db::name('kuyou_customers')->where(['id'=>$detail['customers_id']])->find();
                    $serial= Db::name('kuyou_sets')->where(['name'=>'serial'])->value('is_checked');
                    $batch= Db::name('kuyou_sets')->where(['name'=>'batch'])->value('is_checked');

                    $data = [];
                    $all_number = 0;//总数量
                    $all_price = 0;//总金额
                    foreach ($detail['info_list'] as $k=>$v){
                        if(!empty($v['goods_code'])){//有产品编号
                            if(!isset($v['stores_id']) || empty($v['stores_id'])){
                                return ['status'=>500,'msg'=>'请选择仓库'];
                            }
                            if(!isset($v['number']) || empty($v['number'])){
                                return ['status'=>500,'msg'=>'请输入出库数量'];
                            }
                            $all_number += (float)$v['number'];
                            $all_price += (float)$v['all_money'];

                            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->find();
                            $goods_unit = $v['goods_unit']===''?null:(float)$v['goods_unit'];
                            if(empty($goods_unit)){
                                return ['status'=>500,'msg'=>'请选择单位'];
                            }

                            $advance_rate = 1;//换算进率
                            if($goods['more_unit']==1) {
                                if($goods_unit!=$goods['unit_id']){
                                    //所选单位不等于商品默认单位，需查询进率换算基础数量
                                    $more_unit = Db::name('kuyou_unit_conversion')
                                        ->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$goods_unit])
                                        ->field('id,advance_rate')
                                        ->find();
                                    if(empty($more_unit)){
                                        return ['status'=>500,'msg'=>'商品单位信息查询失败'];
                                    }else{
                                        $advance_rate = $more_unit['advance_rate'];
                                    }
                                }
                            }

                            if($goods['batch']==1 && $batch==1) {
                                if (empty($v['batch_id'])) {
                                    return ['status'=>500,'msg'=>'请选择生产批次'];
                                }
                                if (empty($v['manufacture'])) {
                                    return ['status'=>500,'msg'=>'请输入生产日期'];
                                }
                                if (empty($v['guarantee'])) {
                                    return ['status'=>500,'msg'=>'请输入保质期'];
                                }
                                if (empty($v['validity'])) {
                                    return ['status'=>500,'msg'=>'请输入过期时间'];
                                }
                                $where = [];
                                $where['goods_code'] = $goods['goods_code'];
                                $where['stores_id'] = (float)$v['stores_id'];
                                if(!empty($v['goods_attr'])){
                                    $where['attribute_id'] = (float)$v['goods_attr'];
                                }
                                $where['batch_id'] = (float)$v['batch_id'];
                                $basic_nmber = round(($advance_rate*$v['number']),4);

                                $batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                                if(empty($batch_stock)){
                                    return ['status'=>500,'msg'=>'批次信息查询错误'];
                                }elseif ($batch_stock['stock']<$basic_nmber){
                                    return ['status'=>500,'msg'=>'此批次库存不足'];
                                }
                            }
                            if(isset($v['period_period']) && $goods['serial']==1 && $serial==1){
                                if(empty($v['period_period'])){
                                    return ['status'=>500,'msg'=>'请输入商品序列号'];
                                }
                                $basic_nmber = (float)$v['number'];

                                $per_code = [];
                                $period = $v['period_period'];
                                foreach ($period as $period_k=>$period_v){
                                    if(!in_array($period_v['serial'],$per_code)){
                                        $per_code[] = $period_v['serial'];
                                    }
                                }
                                $per_s = Db::name('kuyou_goods_serial')->where(['serial'=>['in',$per_code],'store_status'=>'1'])->column('serial');
                                if(sizeof($per_code)!=sizeof($per_s)){
                                    $str = [];
                                    foreach ($per_code as $per_code_k=>$per_code_v){
                                        if(!in_array($per_code_v,$per_s)){
                                            $str[] = $per_code_v;
                                        }
                                    }
                                    return ['status'=>500,'msg'=>'序列号'.implode(',',$str).'不在库，不可出库'];
                                }
                            }else{
                                $basic_nmber = round(($advance_rate*$v['number']),4);
                            }

                            $data[] = [
                                'purchase_code'     =>  $code,
                                'purchase_time'     =>  $purchase_time,

                                'goods_id'          =>  $goods['id'],
                                'goods_attr'        =>  $v['goods_attr']===''?null:(float)$v['goods_attr'],
                                'goods_unit'        =>  $goods_unit,
                                'stores_id'         =>  $v['stores_id']===''?null:(float)$v['stores_id'],
                                'stock'             =>  $v['allow_stock']===''?null:(float)$v['allow_stock'],
                                'number'            =>  $v['number']===''?null:(float)$v['number'],
                                'basic_nmber'       =>  $basic_nmber,
                                'period'            =>  $v['period_period']===''?null:(is_array($v['period_period'])?serialize($v['period_period']):$v['period_period']),
                                'unit_price'        =>  $v['unit_price']===''?null:(float)$v['unit_price'],
                                'price'             =>  $v['all_money']===''?null:(float)$v['all_money'],

                                'remark'            =>  $v['remark']===''?null:$v['remark'],
                                'batch'             =>  $v['batch_name']===''?null:$v['batch_name'],
                                'batch_id'          =>  $v['batch_id']===''?null:(float)$v['batch_id'],
                                'manufacture'       =>  $v['manufacture']===''?null:strtotime($v['manufacture']),
                                'guarantee'         =>  $v['guarantee']===''?null:(float)$v['guarantee'],
                                'validity'          =>  $v['validity']===''?null:strtotime($v['validity']),

                                'createtime'        => time(),
                                'updatetime'        => time(),
                            ];
                        }
                    }
                    if(!empty($data)){
                        $rowdata = [
                            'purchase_code'     => $code,
                            'purchase_time'     => $purchase_time,
                            'business_type'     => $business_type,
                            'number'            => $all_number,
                            'price'             => $all_price,
                            'customers_id'      => isset($supplyer['id'])?$supplyer['id']:null,
                            'preparation_id'    => $adminId,
                            'remarks'           => $adminId,
                            'order_id'          => isset($detail['order_id'])?$detail['order_id']:null,
                            'order_type'        => isset($detail['order_type'])?(empty($detail['order_type'])?null:$detail['order_type']):null,
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }

                    if($detail['purchase_code']!=$detail['old_purchase_code']){
                        $purchase_id = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                        if($purchase_id){
                            return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                        }
                    }

                    if($row){
                        $res = false;
                        Db::startTrans();
                        try {
                            //关闭审核功能需先反审核一次已审核数据
                            if($examine!=1 && $row['examine_status']==1){
                                self::examinef($detail['old_purchase_code']);
                            }
                            $rowdata['updatetime'] = time();
                            $res = $model->where(['purchase_code'=>$detail['old_purchase_code']])->update($rowdata);
                            Db::name('kuyou_warehouse_info')->where(['purchase_code'=>$old_purchase_code])->delete();
                            if(!empty($data)){
                                Db::name('kuyou_warehouse_info')->insertAll($data);
                            }
                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            if($examine!=1){
                                try {
                                    $exa = self::examine($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                    return ['status'=>500,'msg'=>$exa['msg']];
                                }
                            }
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'未查询到可更新数据'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 删除
     * @param string $purchase_code
     * @return array
     */
    public static function delDetail($purchase_code){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $purchase_code = explode(',',$purchase_code);
            $model = new Warehouse();
            $examine= (new Commons())->getSet('examine','is_checked');

            $list = $model->where(['purchase_code'=>['in',$purchase_code]])->select();
            foreach ($list as $list_k=>$list_v){
                if($list_v['examine_status']==1 && $examine==1){
                    return ['status'=>500,'msg'=>'不能删除已审核的数据'];
                }
            }
            $count = 0;
            $res = false;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['examine_status']==1 && $examine!=1){
                        try {
                            self::examinef($v['purchase_code']);
                        } catch (Exception $e) {
                        }
                    }
                    $res = $model->where(['purchase_code'=>$v['purchase_code']])->delete();
                    $count += $res;
                    Db::name('kuyou_warehouse_info')->where(['purchase_code'=>$v['purchase_code']])->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 审核
     * @param array $purchase_code
     * @return array
     */
    public static function examine($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }
        $model = new Warehouse();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要审核的数据'];
        }
        $serial= Db::name('kuyou_sets')->where(['name'=>'serial'])->value('is_checked');
        $batch= Db::name('kuyou_sets')->where(['name'=>'batch'])->value('is_checked');

        $editstock = [];
        $goods_stock = [];
        $purchase_info = [];
        $goods_stock_log = [];//收发详情
        $serial_log = [];//序列号跟踪
        $goods_batch_edit = [];
        $goods_batch_log = [];
        $edit_serial = [];
        foreach ($list as $list_k=>$list_v){
            $info_list = Db::name('kuyou_warehouse_info')->where(['purchase_code'=>$list_v['purchase_code']])->select();

            foreach ($info_list as $info_list_k=>$info_list_v){
                $stock_number = $info_list_v['basic_nmber'];
                $goods = Db::name('kuyou_goods')->where(['id'=>$info_list_v['goods_id']])->field('id,goods_code,attribute_id,inventory,batch,serial')->find();
                $status = false;
                foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                    if($goods_stock_v['id']==$goods['id']){
                        $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']-$stock_number;
                        $status = true;
                    }
                }
                if(!$status){
                    $goods_stock[] = [
                        'id'=>$goods['id'],
                        'inventory'=>$goods['inventory']-$stock_number,
                    ];
                }
                //商品库存
                $where = [];
                $where['goods_code'] = $goods['goods_code'];
                $where['stores_id'] = $info_list_v['stores_id'];
                $goods_attr = 0;
                if($info_list_v['goods_attr']>0){
                    $goods_attr = $info_list_v['goods_attr'];
                    if($goods_attr>0){
                        $where['attribute_id'] = $goods_attr;
                    }
                }
                $stock = Db::name('kuyou_goods_stock')->where($where)->field('stock,id,cost_money')->find();
                if($stock){
                    $status = false;
                    foreach ($editstock as $editstock_k=>$editstock_v){
                        if($editstock_v['id']==$stock['id']){
                            $editstock[$editstock_k]['stock'] -= $stock_number;
                            $editstock[$editstock_k]['cost_money'] = (round($editstock_v['cost_money']-$info_list_v['price'],4));
                            $status = true;
                        }
                    }
                    if(!$status){
                        $editstock[] = [
                            'id'=>$stock['id'],
                            'stock'=>(round($stock['stock']-$stock_number,4)),
                            'cost_money'=>(round($stock['cost_money']-$info_list_v['price'],4))
                        ];
                    }
                }else{
                    return ['status'=>500,'msg'=>'库存不足'];
                }
                $purchase_info[] = $info_list_v['id'];
                $supplyer = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_id']])->value('id');

                //收发详情
                if($goods){
                    $goods_stock_log[] = [
                        'purchase_code' => $info_list_v['purchase_code'],
                        'purchase_id'   => $info_list_v['id'],
                        'purchase_time' => $info_list_v['purchase_time'],
                        'business_type' => $list_v['business_type']==1?10:11,
                        'customer_id'   => (float)$supplyer,
                        'goods_id'      => $goods['id'],
                        'goods_code'    => $goods['goods_code'],
                        'attribute_id'  => (float)$info_list_v['goods_attr'],
                        'goods_unit'    => (float)$info_list_v['goods_unit'],
                        'stores_id'     => (float)$info_list_v['stores_id'],
                        'remark'        => $info_list_v['remark'],
                        'out_number'  => (float)$info_list_v['number'],
                        'out_basics'  => (float)$info_list_v['basic_nmber'],
                        'out_unit'    => round($info_list_v['unit_price'],4),
                        'out_cost'    => (float)$info_list_v['price'],
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ];
                }
                //收发详情结束

                //批次跟踪
                if($batch==1 && $goods['batch']==1){
                    $where = [];
                    $where['goods_id'] = $goods['id'];
                    if($goods_attr>0){
                        $where['attribute_id'] = $goods_attr;
                    }
                    $where['stores_id'] = $info_list_v['stores_id'];
                    $where['batch_id'] = $info_list_v['batch_id'];
                    $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                    if(empty($goods_batch_stock)){
                        return ['status'=>500,'msg'=>'批次信息查询失败'];
                    }else{
                        if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                            $goods_batch_edit[$goods_batch_stock['id']] -= $stock_number;
                        }else{
                            $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']-$stock_number;
                        }
                    }
                    //商品批次跟踪
                    $goods_batch_log[] = [
                        'goods_id'      => $goods['id'],
                        'goods_unit'    => $info_list_v['goods_unit'],
                        'stores_id'     => $info_list_v['stores_id'],
                        'batch_id'      => (float)$info_list_v['batch_id'],
                        'number'        => (float)$info_list_v['basic_nmber'],
                        'purchase_code' => $info_list_v['purchase_code'],
                        'purchase_time' => $info_list_v['purchase_time'],
                        'business_type' => $list_v['business_type']==1?9:10,
                        'remarks'       => $info_list_v['remark'],
                        'order_id'      => $info_list_v['id'],
                        'unit_price'    => $info_list_v['unit_price'],
                        'tax_included'  => $info_list_v['unit_price'],
                        'all_money'     => $info_list_v['price'],
                        'tax_money'     => 0,
                        'money_tax_price' => $info_list_v['price'],
                        'customer_id'   => $supplyer,
                        'createtime'    => time(),
                        'updatetime'    => time(),
                    ];
                    //商品批次跟踪结束
                }

                //序列号跟踪
                if($goods && $goods['serial']==1 && $serial==1 && !empty($info_list_v['period'])){
                    $period = unserialize($info_list_v['period']);
                    foreach ($period as $period_k=>$period_v){

                        $per_s = Db::name('kuyou_goods_serial')->where(['serial'=>$period_v['serial']])->field('serial,status,store_status')->find();//序列号
                        if($per_s){//仓库有记录
                            if($per_s['store_status']!=1){
                                return ['status'=>500,'msg'=>'序列号不在库，不可出库'];
                            }
                            $type = Db::name('kuyou_warehouse')->where(['purchase_code'=>$list_v['purchase_code']])->value('business_type');
                            $edit_serial[] = ['serial'=>$per_s['serial'],'warehousing_id'=>$info_list_v['id'],'type'=>($type==1?9:10),'old_status'=>$per_s['status'],'old_store'=>$per_s['store_status']];
                        }else{
                            return ['status'=>500,'msg'=>'序列号查询失败'];
                        }
                        $serial_log[] = [
                            'goods_id'=>$info_list_v['goods_id'],
                            'stores_id'=>$info_list_v['stores_id'],
                            'attribute_id'=>isset($goods_attr)?$goods_attr:0,
                            'serial'=>$period_v['serial'],
                            'business_type'=>$list_v['business_type']==1?9:10,
                            'store_status'=>'1',
                            'remarks' => $period_v['remark'],
                            'purchase_id'=>$info_list_v['id'],
                            'customer_id'=>$supplyer,
                            'purchase_code'=>$info_list_v['purchase_code'],
                            'purchase_time' => $info_list_v['purchase_time'],
                            'order_id'      => $info_list_v['id'],
                            'createtime'  => time(),
                            'updatetime'  => time(),
                        ];
                    }
                }
                //序列号跟踪
            }
        }

        Db::startTrans();
        try {
            $result = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
            if(!empty($editstock)){
                (new GoodsStock())->saveAll($editstock);
            }
            if(!empty($goods_stock)){
                (new Goods())->saveAll($goods_stock);
            }
            //商品收发明细
            if(!empty($goods_stock_log)){
                Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
            }


            //批次库存数据
            //批次
            if(!empty($goods_batch_log)){
                Db::name('kuyou_goods_batch_log')->insertAll($goods_batch_log);
            }
            if(!empty($goods_batch_edit)){
                foreach ($goods_batch_edit as $k=>$v){
                    Db::name('kuyou_goods_batch_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                }
            }
            //批次库存数据结束

            if(!empty($edit_serial)){
                foreach ($edit_serial as $edit_serial_k=>$edit_serial_v){
                    Db::name('kuyou_goods_serial')->where(['serial'=>$edit_serial_v['serial']])->update([
                        'warehoue_id'=>$edit_serial_v['warehousing_id'],
                        'status'=>$edit_serial_v['type'],
                        'store_status'=>'2',
                        'old_status'=>$edit_serial_v['old_status'],
                        'old_store'=>$edit_serial_v['old_store']
                    ]);
                }
            }
            //序列号跟踪
            if(!empty($serial_log)){
                Db::name('kuyou_goods_serial_log')->insertAll($serial_log);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'审核失败'];
        }
    }

    /**
     * 反审核
     * @param array $purchase_code
     * @return array
     */
    public static function examinef($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }
        $batch= Db::name('kuyou_sets')->where(['name'=>'batch'])->value('is_checked');

        $model = new Warehouse();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要反审核的数据'];
        }
        $edit_arr = [];
        foreach ($list as $list_k=>$list_v){
            $info_id = Db::name('kuyou_warehouse_info')->where(['purchase_code'=>$list_v['purchase_code']])->column('id');
            $edit_arr[] = ['business_type'=>$list_v['business_type'],'ids'=>$info_id];
        }
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->column('purchase_code');

        $editstock = [];$goods_stock = [];
        $info_list = Db::name('kuyou_warehouse_info')->where(['purchase_code'=>['in',$list]])->select();

        $purchase_info = [];$goods_batch_edit = [];
        foreach ($info_list as $list_k=>$list_v){
            $stock_number = $list_v['basic_nmber'];
            $goods = Db::name('kuyou_goods')->where(['id'=>$list_v['goods_id']])->field('id,attribute_id,inventory,goods_name,goods_code,batch')->find();

            $status = false;
            foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                if($goods_stock_v['id']==$goods['id']){
                    $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']+$stock_number;
                    $status = true;
                }
            }
            if(!$status){
                $goods_stock[] = [
                    'id'=>$goods['id'],
                    'inventory'=>$goods['inventory']+$stock_number,
                ];
            }

            $where = [];
            $where['goods_code'] = $goods['goods_code'];
            $where['stores_id'] = $list_v['stores_id'];
            $goods_attr = 0;
            if($list_v['goods_attr']>0){
                $goods_attr = $list_v['goods_attr'];
                if($goods_attr>0){
                    $where['attribute_id'] = $goods_attr;
                }
            }
            $stock = Db::name('kuyou_goods_stock')->where($where)->field('stock,id,cost_money')->find();
            if($stock){
                $status = false;
                foreach ($editstock as $editstock_k=>$editstock_v){
                    if($editstock_v['id']==$stock['id']){
                        $editstock[$editstock_k]['stock'] += $stock_number;
                        $editstock[$editstock_k]['cost_money'] = (round($editstock_v['cost_money']+$list_v['price'],4));
                        $status = true;
                    }
                }
                if(!$status){
                    $editstock[] = [
                        'id'=>$stock['id'],
                        'stock'=>(round($stock['stock']+$stock_number,2)),
                        'cost_money'=>(round($stock['cost_money']+$list_v['price'],4))
                    ];
                }
            }else{
                return ['status'=>500,'msg'=>$goods['goods_name'].'库存不足,操作失败'];
            }
            $purchase_info[] = $list_v['id'];

            if($goods['batch']==1 && $batch==1){
                //批次库存数据
                $where = [];
                $where['goods_id'] = $list_v['goods_id'];
                if($goods_attr>0){
                    $where['attribute_id'] = $goods_attr;
                }
                $where['stores_id'] = $list_v['stores_id'];
                $where['batch_id'] = $list_v['batch_id'];
                $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                if(empty($goods_batch_stock)){
                    return ['status'=>500,'msg'=>'库存不足'];
                }else{
                    if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                        $goods_batch_edit[$goods_batch_stock['id']] += $stock_number;
                    }else{
                        $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']+$stock_number;
                    }
                }
            }
        }
        //批次库存数据结束

        Db::startTrans();
        try {
            $result = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->update(['examine_status'=>0,'examine_id'=>0,'examine_time'=>'','operation_id'=>$adminId]);
            //商品详细库存
            if(!empty($editstock)){
                (new GoodsStock())->saveAll($editstock);
            }
            //商品总库存
            if(!empty($goods_stock)){
                (new Goods())->saveAll($goods_stock);
            }
            if(!empty($goods_batch_edit)){
                foreach ($goods_batch_edit as $k=>$v){
                    Db::name('kuyou_goods_batch_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                }
            }

            foreach ($edit_arr as $edit_arr_k=>$edit_arr_v){
                //批次
                $type = $edit_arr_v['business_type']==1?3:4;
                Db::name('kuyou_goods_batch_info')->where(['type'=>$type,'purchase_info_id'=>['in',$edit_arr_v['ids']]])->delete();
                $type = $edit_arr_v['business_type']==1?7:8;
                Db::name('kuyou_goods_batch_log')->where(['business_type'=>$type,'order_id'=>['in',$edit_arr_v['ids']]])->delete();
                Db::name('kuyou_goods_serial_log')->where(['business_type'=>$type,'order_id'=>['in',$edit_arr_v['ids']]])->delete();
                $type = $edit_arr_v['business_type']==1?10:11;
                Db::name('kuyou_goods_log')->where(['business_type'=>$type,'purchase_id'=>['in',$edit_arr_v['ids']]])->delete();

                $serial = Db::name('kuyou_goods_serial')->where(['warehoue_id'=>['in',$edit_arr_v['ids']]])->select();
                foreach ($serial as $serial_k=>$serial_v){
                    Db::name('kuyou_goods_serial')->where(['id'=>$serial_v['id']])->update(['status'=>$serial_v['old_status'],'store_status'=>$serial_v['old_store']]);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'反审核失败'];
        }
    }

}
